<template>
  <div>
    <el-upload
      accept=".png,.jpg,.jpeg"
      :action="uploadUrl"
      name="uploadFile"
      :data="{folder}"

      :before-upload="beforeUpload"
      list-type="picture-card"
      :file-list="fileList"

      :limit="limit"

      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus" />
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过6M</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>

import { uploadUrl } from '@/api/upload'

export default {
  name: 'MultiImageUpload',
  props: {
    // 图片属性数组
    value: {
      type: Array,
      default: () => []
    },
    // 最大上传图片数量
    limit: {
      type: Number,
      default: 5
    },
    folder: {
      type: String,
      default: 'common'
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: null,
      uploadUrl
    }
  },
  computed: {
    fileList() {
      const fileList = []
      for (let i = 0; i < this.value.length; i++) {
        fileList.push({ url: this.value[i] })
      }
      return fileList
    }
  },
  methods: {
    emitInput(fileList) {
      const value = []
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].url)
      }
      this.$emit('input', value)
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList)
    },
    handlePreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt6M = file.size / 1024 / 1024 < 6

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt6M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }

      return isJPG && isLt6M
    },
    handleUploadSuccess(res, file) {
      this.fileList.push({ name: res.data.fileName, url: res.data.fullFilePath })
      this.emitInput(this.fileList)
    },
    handleExceed(files, fileList) {
      this.$message({
        message: '最多只能上传' + this.limit + '张图片',
        type: 'warning',
        duration: 1000
      })
    }
  }
}
</script>
<style>

</style>

